﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Reflection;
using System.IO;
using System.Diagnostics;

namespace template_dll
{
    public partial class ChildForm : Form
    {
        public ChildForm()
        {
            InitializeComponent();
        }

        private const string namechcol = "Флаг";
        private SqlConnection conn;
        private DataTable dt_rep = new DataTable();
        private delegate void Deleg();
        private Deleg del;
        private DateTime date_b;                //- Дата начала отчёта
        private DateTime date_e;                //- Дата окончания отчёта
        private int flag_users = 0;             //- Выводить ли имена пользователей, 0 - не выводить, 1 - выводить
        
        public static bool DisplayForm(System.Windows.Forms.Form theMDIParent)
        {
            ChildForm f = new ChildForm();
            f.MdiParent = theMDIParent;
            f.WindowState = FormWindowState.Maximized;
            f.Show();
            return true;
        }

        private string GetServ(string filename)
        {
            string str = "";
            using (StreamReader streamReader = new StreamReader(filename))
            {
                while (!streamReader.EndOfStream)
                {
                    str += streamReader.ReadLine();
                }
            }
            return str;
        }

        private void ChildForm_Load(object sender, EventArgs e)
        {
            conn = new SqlConnection(@"Server=" + GetServ("serv.txt") + ";Database=SecurityFA;Integrated Security=True");
            dateTimePicker1.Value = DateTime.Now.AddDays(-8);
            dateTimePicker2.Value = DateTime.Now.AddDays(-1);
            date_b = dateTimePicker1.Value;
            date_e = dateTimePicker2.Value;
            checkBox1.Checked = false;
            flag_users = 0;
        }

        private void StartCreateRep(object sender, EventArgs e)
        {
            dataGridView1.DataSource = null;
            dt_rep.Clear();
            del = new Deleg(CreateRep);
            this.Text += " Формируется";
            IAsyncResult asyncRes = del.BeginInvoke(new AsyncCallback(CallBackFunc), null); //
            panel1.Enabled = false;
            dataGridView1.Enabled = false;
        }

        private void CallBackFunc(IAsyncResult aRes)
        {
            del.EndInvoke(aRes);
            panel1.Invoke((Func<bool>)(() => panel1.Enabled = true));
            dataGridView1.Invoke((Func<bool>)(() => dataGridView1.Enabled = true));
            this.Invoke((Func<string>)(() => this.Text = this.Text.Replace(" Формируется", "")));
            dataGridView1.Invoke((Func<object>)(() => dataGridView1.DataSource = dt_rep.DefaultView));
        }

        private void CreateRep()
        {
            if (conn.State == ConnectionState.Closed) conn.Open();
            try
            {
                dt_rep = null;
                dt_rep = new DataTable();
                SqlStorProc.sp_params[] par = new SqlStorProc.sp_params[3];
                par[0].name = "@date_b";
                par[0].value = date_b;
                par[1].name = "@date_e";
                par[1].value = date_e;
                par[2].name = "@flag_users";
                par[2].value = flag_users;

                dt_rep = (new SqlStorProc()).SqlProcExecWithQueryOneTable(conn, "pas_RepToolUsers", 30, par);
                conn.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                conn.Close();
            }

        }

        private SqlDataReader RepProc(SqlConnection sqlcon)//метод для вызова хранимки
        {
            SqlCommand sqlcom = sqlcon.CreateCommand();
            sqlcom.CommandType = CommandType.StoredProcedure;
            sqlcom.CommandText = @"sp_name"; //имя хранимой процедуры
            sqlcom.CommandTimeout = 300;

            

            return sqlcom.ExecuteReader();
        }

        private void ExpToExcel(object sender, EventArgs e)
        {
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.FileName = "csv-file";
            sfd.Filter = "Файл CSV | *.csv";
            if (sfd.ShowDialog() == DialogResult.OK)
            {   
                SaveDGVToCSVfile(sfd.FileName.ToString(), dataGridView1, true);
            }
        }

        public static bool SaveDGVToCSVfile(string filename, DataGridView table, bool openInExcel)
        {
            try
            {
                StreamWriter sw = new StreamWriter(filename, false, Encoding.Unicode);

                List<int> col_n = new List<int>();
                foreach (DataGridViewColumn col in table.Columns)
                    if (col.Visible)
                    {
                        sw.Write(col.HeaderText + "\t");
                        col_n.Add(col.Index);
                    }
                sw.WriteLine();
                int x = table.RowCount;
                if (table.AllowUserToAddRows) x--;

                for (int i = 0; i < x; i++)
                {
                    for (int y = 0; y < col_n.Count; y++)
                        sw.Write(table[col_n[y], i].Value + "\t");
                    sw.Write(" \r\n");
                }
                sw.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Ошибка!", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                return false;
            }

            if (openInExcel)
            {
                try
                {
                    Process newProc = Process.Start("excel.exe", "\"" + filename + "\"");
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Ошибка!", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                }
            }
            return true;
        }

        private void dateTimePicker2_ValueChanged(object sender, EventArgs e)
        {
            //- Дата окончания отчёта
            date_e = dateTimePicker2.Value;
        }

        private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
        {
            //- Дата начала отчёта
            date_b = dateTimePicker1.Value;
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            //- Выводить ли имена пользователей
            if (checkBox1.Checked == false)
            { 
                //- Не показываем имена пользователей
                flag_users = 0;

            }
            else if (checkBox1.Checked == true)
            {
                //- Показываем имена пользователей
                flag_users = 1;
            }

        }

        private void button2_Click(object sender, EventArgs e)
        {
            //- Экспорт в Excel готового отчёта
            ExpToExcel ex = new ExpToExcel();
            ex.SaveDGVToCSVfile("Инструменты АС", dataGridView1, true); 
        }

        private void button3_Click(object sender, EventArgs e)
        {
            flag_users = 2;
            StartCreateRep(button3, null);
        }


    }
}
